﻿using System;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Caching;
using System.Web.Mvc;
using System.Web.Security;
using System.Text;
using System.Threading;

using PortalIntranet.InternalComponents.Common;
using PortalIntranet.InternalComponents.Security;
using PortalIntranet.InternalComponents.Configuration;
using PortalIntranet.BusinessComponents.Seguranca;
using PortalIntranet.DatabaseComponents.Seguranca;
using PortalIntranet.ObjectComponents.Seguranca;

namespace IntranetApplication.Controllers.Login
{
    public class LoginController : Controller
	{
		#region Index
		[AllowAnonymous]
		public ActionResult Index()
		{
			if (HttpContext.User.Identity.IsAuthenticated)
			{
				Usuario usuario = UsuariosBll.Obter(HttpContext.User.Identity.Name.ToLower());

				if (usuario != null)
				{
					RegistrarUsuario(usuario, true);
					return RedirectToAction("Index", "Home");
				}
			}

			return View();
		}
		#endregion

		#region Actions
		[HttpPost]
		[AllowAnonymous]
		public ActionResult Logon(LoginInfo login)
		{
			string email = login.Email.ToLower();
			StringBuilder messages = new StringBuilder(string.Empty);
			Usuario usuario = UsuariosBll.ValidarLogin(email, Cryptography.MD5Hash(login.Senha));

			if (usuario == null)
			{
				messages.Append(HtmlFunc.CreateListItem("O email ou a senha informada são inválidos."));
			}
			else
			{
				RegistrarUsuario(usuario, login.LembrarMe);
			}

			return Json(
				new
				{
					messages = messages.ToString(),
					url = AppSettings.UrlHome
				},
				"application/json"
			);
		}

		[Authorize]
		public ActionResult Logoff()
		{
			DesregistrarUsuario();
			return RedirectToAction("Index", "Login");
		}
		#endregion

		#region Functions
		public void RegistrarUsuario(Usuario usuario, bool lembrar)
		{
			FormsAuthentication.SetAuthCookie(usuario.Email, lembrar);
			HttpContext.Cache.Remove(AppSettings.AuthCacheName);
			UsuarioInfo usuinfo = new UsuarioInfo(usuario);
			HttpContext.Cache.Add(AppSettings.AuthCacheName, usuinfo, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
			UsuariosBll.AtualizarUltimoAcesso(usuario.Id);
		}

		public void DesregistrarUsuario()
		{
			Session.Clear();
			Response.Cookies.Clear();
			HttpContext.Cache.Remove(AppSettings.AuthCacheName);
			FormsAuthentication.SignOut();
		}
		#endregion
	}
}
